package mybatis.session;

import mybatis.builder.xml.XmlConfigBuilder;
import mybatis.exception.MyBatisException;
import mybatis.session.defaults.DefaultSqlSessionFactory;
import org.dom4j.DocumentException;

import java.io.IOException;
import java.io.InputStream;

/**
 * 数据库查询会话对象工厂构造器类
 *
 * @author richie696
 * @version 1.0
 * @since 2020/11/07
 */
public class SqlSessionFactoryBuilder {

    /**
     * 数据库查询会话对象工厂对象构造方法
     *
     * @param inputStream 核心配置文件输入流
     * @return 返回数据库查询会话对象工厂对象
     */
    public SqlSessionFactory build(InputStream inputStream) {
        try (inputStream) {
            // 解析主配置文件
            XmlConfigBuilder xmlConfigBuilder = new XmlConfigBuilder();
            Configuration configuration = xmlConfigBuilder.parse(inputStream);
            // 返回会话工厂
            return new DefaultSqlSessionFactory(configuration);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
            throw new MyBatisException("Error opening session.  Cause: " + e, e);
        }
    }

}
